package com.xiaorong.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaorong.Principal;
import com.xiaorong.dao.CommonDao;


public class BaseController {
	
	public static final int PAGE_SIZE = 10;
	private static final String FLASH_MESSAGE_ATTRIBUTE_NAME = "flashmessage";
	private static final String FLASH_MESSAGE_ATTRIBUTE_TYPE = "flashtype";
	public static final String SUCCESS_MESSAGE = "操作成功";
	public static final String ERROR_MESSAGE = "操作失败";
	public static final String WARN_TYPE = "warn";
	public static final String SUCCESS_TYPE = "success";
	public static final String ERROR_TYPE = "error";
	
	
	@Resource
	protected CommonDao commonDao;
	@Resource
	protected Validator validator;
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}

	protected void addFlashMessage(RedirectAttributes redirectAttributes, String type, String message) {
		if (redirectAttributes != null) {
			redirectAttributes.addFlashAttribute(FLASH_MESSAGE_ATTRIBUTE_NAME, message);
			redirectAttributes.addFlashAttribute(FLASH_MESSAGE_ATTRIBUTE_TYPE, type);
		}
	}
	
	protected String getCurrentDate(String pattern){
		return new SimpleDateFormat(pattern).format(new Date());
	}
	
	protected String getCurrentAdmin(HttpServletRequest request){
		Principal principal = (Principal) request.getSession().getAttribute("adminUsername");
		return principal.getUsername();
	}
	
}
